const fs = require('fs');
const ora = require('ora');
const inquirer = require('inquirer');
const chalk = require('chalk');
const clone = require('git-clone');
const templates = require('../templates');
const handlebars = require('handlebars');

module.exports = program => {
  program
    .command('create <project>')
    .alias('c')
    .description('create a project')
    .option('-t, --type [type]', '选择模板类型：normal|esnext|tsnext')
    .action( async (projectName, options) => {
      let tpl = 'normal';
      if (Object.keys(templates).find(item => item === options.type)) {
        tpl = options.type;
      }
      // console.log('create', projectName, options.type);

      const answers = await inquirer.prompt([
        {
          type: 'input',
          name: 'name',
          message: '请输入项目名称'
        }, {
          type: 'input',
          name: 'description',
          message: '请输入描述信息'
        }, {
          type: 'input',
          name: 'author',
          message: '请输入项目作者'
        }
      ]);
      console.log('answers', answers);


      const spinner = ora({
        prefixText: 'madao'
      }).start(chalk.blue('开始下载模板...'));
      const targetPath = '../' + projectName
      clone(templates[tpl].url, targetPath, error => {
        if (error) {
          console.log(error);
          spinner.fail(chalk.red('下载模板失败'));
        } else {
          spinner.succeed(chalk.green('模板下载完成'));
          const fileName = targetPath + '/package.json';
          const packageJson = fs.readFileSync(fileName, 'utf8');
          // 匹配package.json中的 {{}}， 将里面的内容替换
          const packageResult = handlebars.compile(packageJson)(answers);
          fs.writeFileSync(fileName, packageResult);
          spinner.succeed(chalk.green('complete!'));
        }
      });
    });
}
